import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:rxdart/rxdart.dart';

class CountDownText extends StatefulWidget {
  final String text;
  final int time;
  final VoidCallback click;
  final TextStyle textStyle;

  const CountDownText(
      {Key key, this.text, this.time, @required this.click, this.textStyle})
      : assert(text != null),
        assert(time != null),
        assert(click != null),
        assert(textStyle != null),
        super(key: key);

  @override
  State<StatefulWidget> createState() => _CountDownText();
}

class _CountDownText extends State<CountDownText> {
  bool _click = false;
  int time;
  Stream<int> range;

  void _sendCode() {
    range = Rx.range(widget.time, 0);
    range.interval(Duration(seconds: 1)).doOnListen(() {
      widget.click();
      if (mounted) {
        setState(() {
          time = widget.time;
          _click = true;
        });
      }
    }).listen((value) {
      if (mounted) {
        setState(() {
          time = value;
        });
      }
    }).onDone(() {
      if (mounted) {
        setState(() {
          _click = false;
        });
      }
    });
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return FlatButton(
      padding: EdgeInsets.all(0),
      onPressed: _click
          ? null
          : () {
              _sendCode();
            },
      child: Container(
        child: Text(
          _click ? "等待($time)秒" : widget.text,
          style: widget.textStyle,
        ),
      ),
    );
  }
}
